
import {
  uploadPart,
  uploadMergePart,
} from "@/request/upload";
import { Upload } from "@/util/upload.js"
/**
 * @param file 文件源对象
 * @param {hash, fileTag} 文件内容hash
 * @param size 文件分片大小
 * @param fileName 文件名称
 * @param formData 分片后文件的formData
 * @description 分片上传
 */
export const UploadPart = {
  async tryUploadByChunks(file, hash, currNo, isStuShow, uploadedFileNames, baseFileUrl, taskJson, size = 2097152) { //uploadedFileNames
    const fileChunkList = [];
    const fileName = file.name;
    const fileTag = hash;
    let cur = 0;
    while (cur < file.size) {
      fileChunkList.push({ chunk: file.slice(cur, cur + size) });
      cur += size;
    }
    const chunkCount = fileChunkList.length;
    let uploadedChunkCount = 0;
    for (var i = 0; i < chunkCount; i++) {
      const filePartName = hash + "-" + i
      if (!uploadedFileNames || !uploadedFileNames.includes(filePartName)) {
        const formData = new FormData();
        //
        let blobFile = new File([fileChunkList[i].chunk], filePartName);
        formData.append("file", blobFile);
        formData.append("fileTag", hash);
        formData.append("index", i);
        // formData.append("taskJson", JSON.stringify(taskJson))
        const r = await this.upPart(formData);
        if (r) uploadedChunkCount++;
        else return false
      }else{
        uploadedChunkCount++;
      }
    }
    
    //这里进行合并
    if (uploadedChunkCount == chunkCount) {
      //相当于promise.all
      console.log("finish chunk upload!!!");
      const res = await uploadMergePart({ fileName, fileTag, chunkCount, currNo, isStuShow, baseFileUrl, taskJson});
      return res
    } else return false
  },
  // 文件分片上传
  upPart(formData) {
    return new Promise((resolve, reject) => {
      uploadPart(formData).then((res) => {
        if (res.errno === 0) {
          resolve(res);
        } else {
          Upload.uploadErrorNotify(null, '文件分片，上传失败!',1500)
          resolve(false);
        }
      }).catch(err => {
        Upload.uploadErrorNotify(null, "文件分片，上传失败!", 1500)
        resolve(false)
      });
    });
  },
  // 合并文件分片
  upMergePart(params) {
    // let params = { fileName, fileTag }
    return new Promise((reslove,reject) => {
      uploadMergePart(params).then((res) => {
        if (res.errno === 0) {
          Upload.uploadSuccessNotify(null, 1500)
          reslove(res)
        } else {
          Upload.uploadErrorNotify(null, "文件上传失败!", 1500)
          reslove(false)
        }
      }).catch(err => {
        Upload.uploadErrorNotify(null, "文件上传失败!", 1500)
        reject(false)
      });
    })
  },
}